package com.shwread.android.ui.page;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw10000243.R;
import com.shwread.android.ui.customview.CheckButton;
import com.tgx.tina.android.ipc.framework.IUIPage;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.BookBean;
import logic.beanenum.BookStatus_Enum;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.BookDao;
import logic.util.Util;

/**
 * 本地文件显示界面
 */
public class ExplorerPage extends AbstractUIPage<MainActivity> implements OnClickListener, OnItemClickListener {
    private static ExplorerPage instance;
    private final ArrayList<String> hasLoadBook = new ArrayList<String>();
    ScheduledThreadPoolExecutor scheduled;
    FileFilter mScanFilter = new FileFilter() {

        @Override
        public boolean accept(File file) {
            if (file.isDirectory()) return true;
            String curExt = Util.filterExt(file.getPath());
            for (String ext : Const.SupportExt) {
                if (ext.equalsIgnoreCase(curExt)) {
                    return true;
                }
            }
            return false;
        }
    };
    /**
     * View
     */
    private ImageView imgReturn;
    private Button btnScan;
    private LinearLayout mLayoutFilePathView;
    private TextView tvFilePath;
    private ListView lvFileList;
    private Button cancel_search_file;
    private TextView Popup_Text;
    private TextView return_super_Directory;
    private File[] curfiles;
    private HashMap<Byte, ArrayList<File>> scanFiles = new HashMap<Byte, ArrayList<File>>();
    private BookDao bookMarkDao;
    private PopupWindow popupWindow;
    private FileSecrchListAdapter fileSearchListAdapter;
    private boolean use_search_apater = false;
    private boolean ClickBack = false;

    //	public static ExplorerPage getInstance(MainActivity t) {
    //		if (instance == null) instance = new ExplorerPage(t);
    //		instance.bActivity = t;
    //		return instance;
    //	}
    private View popupContentView;
    private volatile boolean CancelSearch = false;
    private file_search_Task file_Search_Task;
    private FileListAdapter adapter;
    private TextView toastText;
    private Rect rect;
    private PopupWindow ToastPopup;

    public ExplorerPage(MainActivity t) {
        super(t);
    }

    public void setBookInfo(List<BookBean> infos) {
        if (hasLoadBook != null) {
            hasLoadBook.clear();
        }
        if (infos != null) {
            for (BookBean info : infos) {
                if (!hasLoadBook.contains(info.path)) {
                    hasLoadBook.add(info.path);
                }
            }
        }
    }

    public void removeBookInfo(BookBean info) {
        hasLoadBook.remove(info.path);
    }

    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (curMyView != null) {
            return curMyView;
        }
        curMyView = LayoutInflater.from(arg0).inflate(R.layout.file_explorer, null);
        bookMarkDao = BookDao.getInstance(bActivity);
        initView();
        addListener();
        initData();
        return curMyView;
    }

    @Override
    public int enter(IUIPage<?> arg0) {
        setAdapterState(false);
        setData(new File(tvFilePath.getText().toString()));
        if ("/mnt".equals(tvFilePath.getText())) {
            return_super_Directory.setText("");
            mLayoutFilePathView.setClickable(false);
        } else {
            return_super_Directory.setText("上一级");
        }
        return 0;
    }

    @Override
    public int leave(IUIPage<?> arg0) {
        return 0;
    }

    @Override
    public void notifyView(int cmd, Bundle bundle) {
        switch (cmd) {
            default:
                break;
        }
    }

    @Override
    public void setStatus(int arg0) {
    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        return null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.file_explorer_btn_return:
                ClickBack = true;
                bActivity.onBackPressed();
                bActivity.getUIHandler().sendEmptyMessage(DefaultConsts.UPDATEUI_BOOKSHELF_BOOKS_OK);
                break;
            //点击扫描
            case R.id.file_explorer_btn_scan:
                if (use_search_apater) {
                    return;
                }
                file_Search_Task = new file_search_Task();

                if (popupWindow == null) {
                    popupContentView = LayoutInflater.from(bActivity).inflate(R.layout.file_search_popup, null);
                    cancel_search_file = (Button) popupContentView.findViewById(R.id.file_search_cancel);
                    cancel_search_file.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            CancelSearch = true;
                            file_Search_Task.cancel(true);

                            Popup_Text.postDelayed(new Runnable() {

                                @Override
                                public void run() {
                                    popupWindow.dismiss();
                                    lvFileList.setAdapter(fileSearchListAdapter);
                                    fileSearchListAdapter.setFiles(scanFiles.get(Util.SCAN_TYPE_ALL));
                                    scheduled.shutdown();
                                    setAdapterState(true);
                                    return_super_Directory.setText("返回");
                                    mLayoutFilePathView.setClickable(true);
                                }
                            }, 80);
                            //取消搜索
                        }
                    });
                    Popup_Text = (TextView) popupContentView.findViewById(R.id.file_search_popup_text);
                    popupWindow = new PopupWindow(bActivity);
                    popupWindow.setContentView(popupContentView);
                    popupWindow.setBackgroundDrawable(new ColorDrawable(Color.argb(128, 0, 0, 0)));
                    popupWindow.setFocusable(true);
                    popupWindow.setOutsideTouchable(true);
                    popupWindow.setWidth(LayoutParams.MATCH_PARENT);
                    popupWindow.setHeight(LayoutParams.MATCH_PARENT);
                }
                file_Search_Task.execute("");
                popupWindow.showAtLocation(curMyView, Gravity.BOTTOM | Gravity.LEFT, 0, 0);
                break;
            case R.id.file_explorer_path_ll:
                if (use_search_apater) {
                    lvFileList.setAdapter(adapter);
                    setAdapterState(false);

                    if ("/mnt".equals(tvFilePath.getText())) {
                        return_super_Directory.setText("");
                        mLayoutFilePathView.setClickable(false);
                    } else {
                        return_super_Directory.setText("上一级");
                    }

                    adapter.notifyDataSetChanged();

                } else if (!"/mnt".equals(tvFilePath.getText())) {
                    File file = new File((String) tvFilePath.getText());
                    File parentFile = file.getParentFile();
                    setData(parentFile);
                    if ("/mnt".equals(parentFile.getPath())) {
                        return_super_Directory.setText("");
                        mLayoutFilePathView.setClickable(false);
                    }
                } else {
                    File file = new File((String) tvFilePath.getText());
                    File parentFile = file.getParentFile();
                    return_super_Directory.setText("");
                    mLayoutFilePathView.setClickable(false);
                }

                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
        File file = (File) parent.getItemAtPosition(position);

        if (file.isDirectory()) {
            return_super_Directory.setText("上一级");
            mLayoutFilePathView.setClickable(true);
            setData(file);
        } else {
            if (file.length() == 0) {
                showToast(bActivity.getResources().getString(R.string.no_file_context));
            } else if (!hasLoadBook.contains(file.getPath())) {
                addIntoBookShelf(file);
                hasLoadBook.add(file.getPath());
                ((CheckButton) arg1.findViewById(R.id.file_state_btn)).setHaveImportState();
            }
        }
    }

    private void initView() {
        imgReturn = (ImageView) curMyView.findViewById(R.id.file_explorer_btn_return);
        btnScan = (Button) curMyView.findViewById(R.id.file_explorer_btn_scan);

        lvFileList = (ListView) curMyView.findViewById(R.id.file_explorer_list);
        tvFilePath = (TextView) curMyView.findViewById(R.id.file_explorer_path_text);
        tvFilePath.setText("/mnt/sdcard");
        mLayoutFilePathView = (LinearLayout) curMyView.findViewById(R.id.file_explorer_path_ll);
        return_super_Directory = (TextView) curMyView.findViewById(R.id.file_explorer_parent);

    }

    private void addListener() {
        imgReturn.setOnClickListener(this);
        btnScan.setOnClickListener(this);
        mLayoutFilePathView.setOnClickListener(this);
    }

    private void addIntoBookShelf(File file) {

        int status = BookStatus_Enum.LOCAL.getValue();
        String ffname = file.getName().substring((file.getName().length() - file.getName().lastIndexOf(".")), file.getName().length());
        int bookType = 1;
        if ("umd".equals(ffname)) bookType = 4;
        else if ("mp3".equals(ffname)) bookType = 5;
        BookBean info = new BookBean(status, -1, file.getName(), bookType, 0, file.getPath(), "佚名", Const.phone_number, String.valueOf(-System.currentTimeMillis()), "");

        boolean res = bookMarkDao.addBooktoShelf(info);
        Util.showToast(bActivity, res ? "导入成功" : "导入失败，请稍候再试");
    }

    private boolean setData(File file) {
        if (file == null || !file.isDirectory()) return false;
        tvFilePath.setText(file.getPath());
        curfiles = file.listFiles(mScanFilter);
        if (curfiles == null) curfiles = new File[]{};
        Arrays.sort(curfiles, new FileComparator());

        adapter = new FileListAdapter(curfiles);
        lvFileList.setAdapter(adapter);

        if (fileSearchListAdapter == null) {
            fileSearchListAdapter = new FileSecrchListAdapter();
            lvFileList.setOnItemClickListener(this);
        }

        if (curfiles.length == 0) {
            Util.ToastShow(context, R.string.no_file_found);
        }
        adapter.notifyDataSetChanged();
        return true;
    }

    @Override
    public boolean isDisposable() {

        return false;
    }

    private void gotoScan(File f) throws Exception {

        if (CancelSearch) {
            throw new Exception("");
        }
        if (f != null && f.exists() && f.isDirectory()) {
            File[] files = f.listFiles();
            if (files != null) {
                for (File file : f.listFiles()) {
                    if (file.isDirectory()) {
                        if (!isCanFind(file.getPath())) {
                            continue;
                        }
                        if (!file.getAbsolutePath().startsWith(".")) {
                            gotoScan(file);
                        }
                    } else if (Util.isReaderFileType(file)) {
                        addReadTypeFile(file);
                    }
                }
            }
        }
    }

    private boolean is_CanAdd(String FileName) {
        ArrayList<File> files = scanFiles.get(Util.SCAN_TYPE_ALL);
        for (File file : files) {
            if (file.getName().equals(FileName)) {
                return true;
            }
        }
        return false;
    }

    private void addReadTypeFile(File file) {
        byte type = Util.getType(file);
        if (type != Util.SCAN_TYPE_ALL) scanFiles.get(type).add(file);
        scanFiles.get(Util.SCAN_TYPE_ALL).add(file);
    }

    private void initData() {
        scanFiles.put(Util.SCAN_TYPE_ALL, new ArrayList<File>());
        scanFiles.put(Util.SCAN_TYPE_TXT, new ArrayList<File>());
        scanFiles.put(Util.SCAN_TYPE_EPUB, new ArrayList<File>());
        scanFiles.put(Util.SCAN_TYPE_OFFICE, new ArrayList<File>());
        scanFiles.put(Util.SCAN_TYPE_OTHER, new ArrayList<File>());
    }

    //	epub txt doc
    private boolean File_CanImport(String Path) {
        if (TextUtils.isEmpty(Path)) {
            return false;
        }
        for (String name : hasLoadBook) {
            if (TextUtils.isEmpty(name)) {
                continue;
            }
            if (name.endsWith(Path)) {
                return true;
            }
        }
        return false;
    }

    private void setAdapterState(boolean state) {
        use_search_apater = state;
    }

    @Override
    public boolean handleBack() {
        if (ClickBack) {
            ClickBack = false;
            return false;
        } else if (use_search_apater) {
            setAdapterState(false);
            lvFileList.setAdapter(adapter);
            return_super_Directory.setText("上一级");
            return true;
        } else if (!"/mnt".equals(tvFilePath.getText())) {
            File file = new File((String) tvFilePath.getText());
            File parentFile = file.getParentFile();
            setData(parentFile);
            if ("/mnt".equals(parentFile.getPath())) {
                return_super_Directory.setText("");
                mLayoutFilePathView.setClickable(false);
            }
            return true;
        } else {
            File file = new File((String) tvFilePath.getText());
            File parentFile = file.getParentFile();
            return_super_Directory.setText("");
            mLayoutFilePathView.setClickable(false);
        }
        return super.handleBack();
    }

    private boolean isCanFind(String Path) {
        if (!TextUtils.isEmpty(Path)) {
            if (Path.startsWith("/mnt")) {
                return true;
            }
        }
        return false;
    }

    void showToast(String content) {
        if (ToastPopup == null) {
            ToastPopup = new PopupWindow(bActivity);
            View v = View.inflate(bActivity, R.layout.toast_popup_layout, null);

            toastText = (TextView) v.findViewById(R.id.toast_popup_layout_text);
            int Height = (int) bActivity.getResources().getDimension(R.dimen.toastpopup_height);
            ToastPopup.setContentView(v);
            ToastPopup.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
            ToastPopup.setBackgroundDrawable(new ColorDrawable(bActivity.getResources().getColor(R.color.Popup_bg)));
            ToastPopup.setHeight(Height);
            rect = new Rect();
            mLayoutFilePathView.getGlobalVisibleRect(rect);
        }
        toastText.setText(content);
        ToastPopup.showAtLocation(curMyView, Gravity.NO_GRAVITY, 0, rect.top);
        toastText.postDelayed(new Runnable() {

            @Override
            public void run() {
                ToastPopup.dismiss();
            }
        }, 1000);
    }

    private class FileListAdapter extends BaseAdapter {
        private File[] mFiles;

        public FileListAdapter(File[] files) {
            mFiles = files;
        }

        @Override
        public int getCount() {
            return mFiles.length;
        }

        @Override
        public Object getItem(int position) {
            return mFiles[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View layout = null;
            if (convertView == null) {
                layout = LayoutInflater.from(context).inflate(R.layout.file_explorer_item, null);
            } else {
                layout = convertView;
            }
            ImageView imageView = (ImageView) layout.findViewById(R.id.file_explorer_item_icon);
            TextView text = (TextView) layout.findViewById(R.id.file_explorer_item_text);
            TextView itemSize = (TextView) layout.findViewById(R.id.file_explorer_item_item_size);
            CheckButton checkButton = (CheckButton) layout.findViewById(R.id.file_state_btn);
            File file = mFiles[position];
            if (file.isDirectory()) {
                imageView.setImageResource(R.drawable.netdisk_icon_folder);
                String[] paths = file.list();
                int count = 0;
                if (paths != null) count = paths.length;
                itemSize.setText(Util.getFileItemCount(context, String.valueOf(count)));
                checkButton.setVisibility(View.GONE);
            } else {
                checkButton.setVisibility(View.VISIBLE);
                imageView.setImageResource(R.drawable.netdisk_icon_default);
                if (File_CanImport(file.getName())) {
                    checkButton.setHaveImportState();
                } else {
                    itemSize.setText(Util.getFileSizeString(file.length()));
                    checkButton.setCanImportState();
                }
            }
            text.setText(file.getName());
            return layout;
        }
    }

    class FileComparator implements Comparator<File> {

        public final static byte BY_NAME = 0;
        public final static byte BY_TIME = 1;
        public final static byte BY_SIZE = 2;

        public int mType = BY_NAME;

        public void setType(byte type) {
            mType = type;
        }

        @Override
        public int compare(File lhs, File rhs) {
            if ((lhs.isDirectory() == rhs.isDirectory())) {
                switch (mType) {
                    case BY_NAME:
                        return lhs.getName().compareToIgnoreCase(rhs.getName());
                    case BY_TIME:
                        long ll = lhs.lastModified() - rhs.lastModified();
                        if (ll > 0) {
                            return 1;
                        } else if (ll == 0) {
                            return 0;
                        } else if (ll < 0) {
                            return -1;
                        }
                        break;
                    case BY_SIZE:
                        long ls = lhs.length() - rhs.length();
                        if (ls > 0) {
                            return 1;
                        } else if (ls == 0) {
                            return 0;
                        } else if (ls < 0) {
                            return -1;
                        }
                        break;
                }
            } else {
                return lhs.isDirectory() ? 1 : -1;
            }
            return 0;
        }
    }

    class file_search_Task extends AsyncTask<String, Integer, String> {

        ArrayList<File> All_File = scanFiles.get(Util.SCAN_TYPE_ALL);

        @Override
        protected String doInBackground(String... params) {
            try {
                CancelSearch = false;
                scheduled = new ScheduledThreadPoolExecutor(1);
                scheduled.scheduleAtFixedRate(new Runnable() {

                    @Override
                    public void run() {
                        Popup_Text.post(new Runnable() {

                            @SuppressLint("StringFormatMatches")
                            @Override
                            public void run() {
                                Popup_Text.setText(String.format(bActivity.getResources().getString(R.string.file_search_text_format, All_File.size())));
                            }
                        });
                    }
                }, 0, 100, TimeUnit.MILLISECONDS);
                All_File.clear();
                String Path = tvFilePath.getText().toString();
                File file = new File(Path);
                gotoScan(file);
            } catch (Exception e) {
                bActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        Util.showToast(bActivity, "扫描失败！");
                    }
                });
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            Popup_Text.setText(bActivity.getString(R.string.file_search_text_format, scanFiles.get(Util.SCAN_TYPE_ALL).size()));
        }

        @Override
        protected void onPostExecute(String result) {
            lvFileList.setAdapter(fileSearchListAdapter);
            fileSearchListAdapter.setFiles(scanFiles.get(Util.SCAN_TYPE_ALL));
            scheduled.shutdown();
            popupWindow.dismiss();
            setAdapterState(true);
            return_super_Directory.setText("返回");
            mLayoutFilePathView.setClickable(true);
            if (fileSearchListAdapter.getCount() < 1) {
                Util.showToast(bActivity, "没有可导入的文件哦");
            }
            super.onPostExecute(result);
        }
    }

    private class FileSecrchListAdapter extends BaseAdapter {
        private ArrayList<File> mFiles;

        public FileSecrchListAdapter() {
        }

        public ArrayList<File> getmFiles() {
            return mFiles;
        }

        public void setFiles(ArrayList<File> files) {
            this.mFiles = files;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            if (mFiles != null) return mFiles.size();
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return mFiles.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View layout = null;
            if (convertView == null) {
                layout = LayoutInflater.from(context).inflate(R.layout.file_explorer_item, null);
            } else {
                layout = convertView;
            }
            ImageView imageView = (ImageView) layout.findViewById(R.id.file_explorer_item_icon);
            TextView text = (TextView) layout.findViewById(R.id.file_explorer_item_text);
            TextView itemSize = (TextView) layout.findViewById(R.id.file_explorer_item_item_size);
            CheckButton checkButton = (CheckButton) layout.findViewById(R.id.file_state_btn);
            File file = mFiles.get(position);

            imageView.setImageResource(R.drawable.netdisk_icon_default);
            if (File_CanImport(file.getName())) {
                checkButton.setHaveImportState();
            } else {
                itemSize.setText(Util.getFileSizeString(file.length()));
                checkButton.setCanImportState();
            }
            text.setText(file.getName());
            return layout;
        }

    }
}
